package com.jeffse.light.stream.core.utils;

import net.sf.ehcache.CacheManager;
import net.sf.ehcache.config.CacheConfiguration;
import net.sf.ehcache.Cache;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

public class CacheUtils implements Serializable {
    private CacheManager cacheManager = CacheManager.getInstance();
    private Map<String, Cache> cacheMap = new HashMap<>();
    private static CacheUtils INSTANCE = new CacheUtils();

    public static CacheUtils getINSTANCE(){
        return INSTANCE;
    }

    public Cache getCache(String cacheName){
        if(cacheMap.get(cacheName) == null){
            Cache cache = getOrAddCache("myCache");
            CacheConfiguration config = cache.getCacheConfiguration();
            config.setTimeToIdleSeconds(60);
            config.setTimeToLiveSeconds(120);
            cacheMap.put(cacheName, cache);
        }

        return cacheMap.get(cacheName);
    }

    public Cache getOrAddCache(String cacheName) {
        Cache cache = cacheManager.getCache(cacheName);
        if (cache == null) {
            synchronized (this) {
                cache = cacheManager.getCache(cacheName);
                if (cache == null) {
                    cacheManager.addCacheIfAbsent(cacheName);
                    cache = cacheManager.getCache(cacheName);
                }
            }
        }
        return cache;
    }
}
